<template>
  <!-- 编辑个人信息组件 :visible.sync显示侧边栏 direction侧边栏打开方向 -->
  <el-drawer :visible.sync="showDrawer" title="编辑个人信息" direction="rtl" size="40%">
    <el-form :model="editInfo" status-icon :rules="rules" ref="editInfo" label-width="100px">
      <el-form-item label="身份证号" prop="card">
        <el-input type="text" v-model="editInfo.card" placeholder="请输入身份证号" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input type="text" v-model="editInfo.phone" placeholder="请输入手机号" autocomplete="off" />
      </el-form-item>
      <el-form-item label="居住地址" prop="address">
        <el-input type="textarea" v-model="editInfo.address" placeholder="请输入居住地址" autocomplete="off" autosize />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload class="avatar-uploader" :on-change="uploadAvatar" :show-file-list="false" :auto-upload="false"
          action="#">
          <img v-if="avatarUrl" :src="avatarUrl" class="avatar" alt="" />
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('editInfo')">提交</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<script>
import { updateInfo } from '@/api/common'

export default {
  name: 'EditInfo', // 编辑个人信息组件
  props: {
    info: {
      require: true,
      type: Object
    },
    identify: {
      require: true,
      type: String
    }
  },
  data () {
    // 身份证号校验
    const checkCard = (rule, value, callback) => {
      // 身份证号分为 18位 15位
      const card18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      const card15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
      if (card18.test(value) || card15.test(value) || value === '') return callback()
      callback(new Error('身份证格式错误'))
    }
    return {
      showDrawer: false, // 显示侧边栏true
      avatarUrl: '', // 展示头像图片的url
      // 存放编辑的个人信息
      editInfo: {
        card: '', // 身份证号
        phone: '', // 手机号
        address: '', // 地址
        avatarFile: '' // 头像图片文件
      },
      // 设置对应的校验规则
      rules: {
        card: [{ validator: checkCard, trigger: 'blur' }],
        phone: [
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式错误',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 显示弹层
    openDrawer () {
      this.showDrawer = true
      this.editInfo = { ...this.info } // 父组件ViewInfo的数据传给子组件

      // 对传递过来的数据进行一些处理 将avatar属性名替换为avatarFile 方便后端接收
      this.$set(this.editInfo, 'identify', this.identify)
      this.$set(this.editInfo, 'avatarFile', this.info.avatar)
      this.$delete(this.editInfo, 'avatar')

      // 如果已有头像则回显头像
      this.avatarUrl = this.editInfo.avatarFile
    },
    // 重置表单
    resetForm () {
      this.editInfo = { ...this.info } // 重置表单数据
      this.avatarUrl = this.info.avatar // 头像路径也需要重置
    },
    // 提交表单 发送请求
    submitForm (editInfo) {
      // 校验数据是否合法
      this.$refs[editInfo].validate(async (valid) => {
        if (valid) {
          // 如果头像没有被修改 就不上传头像
          if (this.avatarUrl === this.info.avatar) this.$delete(this.editInfo, 'avatarFile')

          // 将普通对象转换成FormData对象
          const formData = new FormData()
          for (const key in this.editInfo) formData.append(key, this.editInfo[key])

          await updateInfo(formData)
          this.$message.success('编辑成功！')
          // 编辑成功后关闭侧边栏并通知父组件更新页面
          this.showDrawer = false
          this.$emit('successEdit')
        }
      })
    },
    // 上传图片
    uploadAvatar (uploadAvatar) {
      // 上传头像前对图片进行校验
      const isJPG = uploadAvatar.raw.type === 'image/jpeg'
      const isLt2M = uploadAvatar.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return
      }

      // 使用URL.createObjectURL()方法可以生成图片的临时路径
      this.avatarUrl = URL.createObjectURL(uploadAvatar.raw) // 预览图片
      // 将图片存入avatarFile属性中 用于提交
      this.editInfo.avatarFile = uploadAvatar.raw
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
